import { getInfo } from "@/api/current";
import { token } from "@/utils";

const storage = {
  key: "__VUEX_STATE_USER",
  set: (values) => uni.setStorageSync(storage.key, values),
  get: () => uni.getStorageSync(storage.key),
  remove: () => uni.removeStorageSync(storage.key),
};

const user = {
  state: storage.get() || {},

  mutations: {
    SET_USER: (state, values) => {
      state.user = values;
    },
    SET_ROLES: (state, values) => {
      state.roles = values;
    },
    SET_MENUS: (state, values) => {
      state.menus = values;
    },
    SET_ROUTERS: (state, values) => {
      state.routers = values;
    },
    SET_PERMISSIONS: (state, values) => {
      state.permissions = values;
    },
  },

  actions: {
    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo()
          .then((res) => {
            commit("SET_USER", res.user);
            commit("SET_ROLES", res.user.roles);
            commit("SET_ROUTERS", res.routers);
            commit("SET_MENUS", res.menus);
            commit("SET_PERMISSIONS", res.permissions);

            storage.set(state);
            resolve(res);
          })
          .catch((error) => reject(error));
      });
    },
    LoginOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        commit("SET_USER", {});
        commit("SET_ROUTERS", []);
        commit("SET_MENUS", []);
        commit("SET_PERMISSIONS", []);
        token.removeToken();
        resolve();
      });
    },
  },
};

export default user;
